import csv
import json
import os
import shutil
import time

import pandas as pd
import os
from PIL import Image


def get_direct_subdirectories(directory):
    """
    获取目录下的直接子文件夹（不递归）。

    :param directory: 要检查的目录路径。
    """
    try:
        for entry in os.scandir(directory):
            if entry.is_dir():
                yield entry.path
    except FileNotFoundError:
        print(f"目录 {directory} 不存在")
    except PermissionError:
        print(f"没有权限访问目录 {directory}")


def calculate_crop_box_by_ratio(img, ratio):
    """
    根据给定的比例计算裁切框。

    :param img: 图片对象
    :param ratio: 要裁切的比例 (width_ratio, height_ratio)
    :return: 裁切框 (left, upper, right, lower)
    """
    width, height = img.size
    target_width = int(width * ratio[0])
    target_height = int(height * ratio[1])

    left = (width - target_width) / 2
    upper = (height - target_height) / 2
    right = (width + target_width) / 2
    lower = (height + target_height) / 2

    return (int(left), int(upper), int(right), int(lower))


def crop_and_concat_images(img_paths, output_path, crop_boxes):
    """
    根据给定的裁切框裁剪图片，并垂直拼接它们。

    :param img_paths: 图片文件路径列表
    :param output_path: 输出图片路径
    :param crop_boxes: 裁切框列表，每个元素是一个四元组(left, upper, right, lower)
    """
    images = [Image.open(path) for path in img_paths]
    cropped_images = [img.crop(box) for img, box in zip(images, crop_boxes)]

    # 获取最大宽度和总高度
    widths, heights = zip(*(i.size for i in cropped_images))
    max_width = max(widths)
    total_height = sum(heights)

    # 创建新的图像
    new_img = Image.new('RGB', (max_width, total_height))

    # 粘贴图片
    y_offset = 0
    for img in cropped_images:
        new_img.paste(img, (0, y_offset))
        y_offset += img.height

    # 保存结果
    new_img.save(output_path)


def copy_png_files_from_a_to_b(src_root, dst_root):
    """
    遍历src_root目录下的所有子文件夹，查找每个子文件夹中的'png'文件夹，
    并将其中名为'a'的文件复制到dst_root/C/中，文件名前缀为上层文件夹名称。

    :param src_root: 源文件夹路径（文件夹A）
    :param dst_root: 目标文件夹路径（文件夹B），将在其下创建'C'文件夹
    """

    # 创建目标文件夹B及其内部的C文件夹
    destination_folder = dst_root
    if not os.path.exists(destination_folder):
        os.makedirs(destination_folder)

    for subdir in os.listdir(src_root):
        subdir_path = os.path.join(src_root, subdir)

        # 确保我们只处理文件夹
        if os.path.isdir(subdir_path):
            png_folder_path = os.path.join(subdir_path, 'png')

            name_list = ["all_pass_rate_data.png", "car_pass_rate_data.png", "car_slow_move_data.png",
                         "car_time_data.png", "mate_flow_data.png", "time_duration_data_all.png",
                         "time_duration_data_car.png"]

            # 检查是否存在名为'png'的文件夹
            if os.path.exists(png_folder_path) and os.path.isdir(png_folder_path):
                # 查找并复制名为'a'的文件
                for item in os.listdir(png_folder_path):
                    if item in name_list:  # 假设文件名为'a'
                        source_file = os.path.join(png_folder_path, item)
                        prefix, suffix = os.path.splitext(item)
                        floder = os.path.join(destination_folder, prefix)
                        if not os.path.exists(floder):
                            os.makedirs(floder)
                        if os.path.isfile(source_file):
                            # 构建新的文件名，前缀为上层文件夹名称
                            new_filename = f"{subdir}.{suffix}"
                            destination_file = os.path.join(floder, new_filename)
                            shutil.copy2(source_file, destination_file)
                            print(f"Copied file from {source_file} to {destination_file}")


def copy_png_images(source_folder, destination_folder):
    # 检查源文件夹是否存在
    if not os.path.exists(source_folder):
        print(f"源文件夹 {source_folder} 不存在。")
        return False
    # 检查目标文件夹是否存在，不存在则创建
    if not os.path.exists(destination_folder):
        os.makedirs(destination_folder)
    # 遍历源文件夹
    for root, dirs, files in os.walk(source_folder):
        for file in files:
            # 检查文件扩展名是否为 .png
            if file.lower().endswith('.png'):
                source_file_path = os.path.join(root, file)
                destination_file_path = os.path.join(destination_folder, file)
                try:
                    # 复制文件
                    shutil.copy2(source_file_path, destination_file_path)
                    print(f"已复制文件: {source_file_path} 到 {destination_file_path}")
                except Exception as e:
                    print(f"复制文件 {source_file_path} 时出错: {e}")
    return True


def lindian():
    d_path = r'D:\GJ\项目\事故检测\output\邻垫高速'
    dd_path = r'D:\GJ\项目\事故检测\output_dist'
    csv_file_path = r'D:\GJ\项目\事故检测\output\邻垫高速\event.csv'
    event_file_path = r'D:\GJ\项目\事故检测\xlsx\邻垫路事故汇总11.xlsx'
    event_true_dict = {}
    # 读取 Excel 文件
    df = pd.read_excel(event_file_path)
    # 遍历 DataFrame 的每一行
    for index, row_i in df.iterrows():
        up = str(row_i["事故最近门架编号1"])
        if up not in event_true_dict.keys():
            event_true_dict[up] = {}
            event_true_dict[up]["list"] = []
            event_true_dict[up]["down"] = str(row_i["事故最近门架编号2"])
        dd = {}
        dd["年"] = str(row_i["年"])
        dd["月"] = '{:02d}'.format(row_i["月"])
        dd["日"] = '{:02d}'.format(row_i["日"])
        dd["时"] = '{:02d}'.format(row_i["时"])
        dd["分"] = '{:02d}'.format(row_i["分"])
        dd["方向"] = str(row_i["方向"])
        dd["桩号"] = str(row_i["桩号"])
        dd["道路类型"] = str(row_i["道路类型"])
        dd["事故分类"] = str(row_i["事故分类"])
        event_true_dict[up]["list"].append(dd)

    with open(csv_file_path, 'r', encoding='utf-8') as csvfile:
        true_value_list = []
        reader = csv.DictReader(csvfile)
        for row in reader:
            km = int(int(row["dist"]) / 1000)
            new_path = os.path.join(dd_path, str(km) + "km", "未知")
            if not os.path.exists(new_path):
                os.makedirs(new_path)
            new_floder_name = str(row["gantry_up"]) + "-" + str(row["gantry_down"]) + "-" \
                              + str(row["year"]) + str(row["month"]) + str(row["day"])
            new_floder = os.path.join(new_path, new_floder_name)

            old_floder_name = str(row["gantry_up"]) + "," + str(row["gantry_down"]) + "-" \
                              + str(row["year"]) + str(row["month"]) + str(row["day"])

            copy_png_images(os.path.join(d_path, old_floder_name, "png"), new_floder)

            event_dict1 = event_true_dict[str(row["gantry_up"])]
            event_dict_list = event_dict1["list"]
            if event_dict_list:
                for event_dict in event_dict_list:
                    if event_dict["年"] == str(row["year"]) and event_dict["月"] == str(row["month"]) and event_dict["日"] == str(row["day"]):
                        true_dict = {
                            "eventTime": str(event_dict["年"])+"-"+str(event_dict["月"])+"-"+str(event_dict["日"])+" "
                                         +str(event_dict["时"])+":"+str(event_dict["分"]),
                            "direction": str(event_dict["方向"]),
                            "pileNumber": str(event_dict["桩号"]),
                            "roadType": str(event_dict["道路类型"]),
                            "eventType": str(event_dict["事故分类"])
                        }
                        true_value_list.append(true_dict)
            json_data = {
                "upGantryId": str(row["gantry_up"]),
                "downGantryId": str(row["gantry_down"]),
                "time": str(row["year"])+"-"+str(row["month"])+"-"+str(row["day"]),
                "source": "邻垫高速",
                "trueValueList": true_value_list
            }
            file_path = os.path.join(new_floder, "info.json")
            # 将字典保存为 JSON 文件
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(json_data, f, ensure_ascii=False)

            true_value_list = []


def mianguang():
    d_path = r'D:\GJ\项目\事故检测\output\绵广高速'
    dd_path = r'D:\GJ\项目\事故检测\output_dist'
    csv_file_path = r'D:\GJ\项目\事故检测\output\绵广高速\event.csv'
    event_file_path = r'D:\GJ\项目\事故检测\xlsx\绵广路段交通事故统计表111.xlsx'
    event_true_dict = {}
    # 读取 Excel 文件
    df = pd.read_excel(event_file_path)
    # 遍历 DataFrame 的每一行
    for index, row_i in df.iterrows():
        up = str(row_i["事故最近门架编号1"])
        if up not in event_true_dict.keys():
            event_true_dict[up] = {}
            event_true_dict[up]["list"] = []
            event_true_dict[up]["down"] = str(row_i["事故最近门架编号2"])
        dd = {}
        dd["年"] = str(row_i["年"])
        dd["月"] = '{:02d}'.format(row_i["月"])
        dd["日"] = '{:02d}'.format(row_i["日"])
        dd["时"] = '{:02d}'.format(row_i["时"])
        dd["分"] = '{:02d}'.format(row_i["分"])
        dd["方向"] = str(row_i["方向"])
        dd["桩号"] = str(row_i["桩号"])
        dd["道路类型"] = str(row_i["道路类型"])
        dd["事故分类"] = str(row_i["事故分类"])
        event_true_dict[up]["list"].append(dd)

    up_id = None
    down_id = None
    with open(csv_file_path, 'r', encoding='utf-8') as csvfile:
        true_value_list = []
        reader = csv.DictReader(csvfile)
        for row in reader:
            km = int(int(row["dist"]) / 1000)
            new_path = os.path.join(dd_path, str(km) + "km", "未知")
            if not os.path.exists(new_path):
                os.makedirs(new_path)
            up_id = str(row["gantry_up"])
            down_id = str(row["gantry_down"])
            year = str(row["year"])
            month = str(row["month"])
            day = str(row["day"])
            new_floder_name = up_id + "-" + down_id + "-" + year + month + day
            new_floder = os.path.join(new_path, new_floder_name)

            old_floder_name = up_id + "-" + down_id + "-" + year + "-" + month + "-" + day + "-流水"

            flag = copy_png_images(os.path.join(d_path, old_floder_name, "png"), new_floder)
            if not flag:
                up_id = str(row["gantry_down"])
                down_id = str(row["gantry_up"])
                old_floder_name = up_id + "-" + down_id + "-" + year + "-" + month + "-" + day + "-流水"
                copy_png_images(os.path.join(d_path, old_floder_name, "png"), new_floder)

            if up_id in event_true_dict.keys():
                event_dict1 = event_true_dict[up_id]
                if down_id == event_dict1["down"]:
                    event_dict_list = event_dict1["list"]
            if event_dict_list:
                for event_dict in event_dict_list:
                    if event_dict["年"] == year and event_dict["月"] == month and event_dict["日"] == day:
                        true_dict = {
                            "eventTime": str(event_dict["年"]) + "-" + str(event_dict["月"]) + "-" + str(
                                event_dict["日"]) + " " + str(event_dict["时"]) + ":" + str(event_dict["分"]),
                            "direction": str(event_dict["方向"]),
                            "pileNumber": str(event_dict["桩号"]),
                            "roadType": str(event_dict["道路类型"]),
                            "eventType": str(event_dict["事故分类"])
                        }
                        true_value_list.append(true_dict)
            json_data = {
                "upGantryId": str(row["gantry_up"]),
                "downGantryId": str(row["gantry_down"]),
                "time": str(row["year"]) + "-" + str(row["month"]) + "-" + str(row["day"]),
                "source": "绵广高速",
                "trueValueList": true_value_list
            }
            file_path = os.path.join(new_floder, "info.json")
            # 将字典保存为 JSON 文件
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(json_data, f, ensure_ascii=False)
            true_value_list = []


def naqian():
    d_path = r'D:\GJ\项目\事故检测\output\纳黔高速'
    dd_path = r'D:\GJ\项目\事故检测\output_dist'
    csv_file_path = r'D:\GJ\项目\事故检测\output\纳黔高速\event.csv'
    event_file_path = r'D:\GJ\项目\事故检测\xlsx\纳黔高速路段事件事故附近门架信息表11.xlsx'
    event_true_dict = {}
    # 读取 Excel 文件
    df = pd.read_excel(event_file_path)
    # 遍历 DataFrame 的每一行
    for index, row_i in df.iterrows():
        up = str(row_i["事故最近门架编号1"])
        if up not in event_true_dict.keys():
            event_true_dict[up] = {}
            event_true_dict[up]["list"] = []
            event_true_dict[up]["down"] = str(row_i["事故最近门架编号2"])
        dd = {}
        dd["年"] = str(row_i["年"])
        dd["月"] = '{:02d}'.format(row_i["月"])
        dd["日"] = '{:02d}'.format(row_i["日"])
        dd["时"] = '{:02d}'.format(row_i["时"])
        dd["分"] = '{:02d}'.format(row_i["分"])
        dd["方向"] = str(row_i["方向"])
        dd["桩号"] = str(row_i["桩号"])
        dd["道路类型"] = str(row_i["道路类型"])
        dd["事故分类"] = str(row_i["事故分类"])
        event_true_dict[up]["list"].append(dd)

    up_id = None
    down_id = None
    with open(csv_file_path, 'r', encoding='utf-8') as csvfile:
        true_value_list = []
        reader = csv.DictReader(csvfile)
        for row in reader:
            km = int(int(row["dist"]) / 1000)
            new_path = os.path.join(dd_path, str(km) + "km", "未知")
            if not os.path.exists(new_path):
                os.makedirs(new_path)
            up_id = str(row["gantry_up"])
            down_id = str(row["gantry_down"])
            year = str(row["year"])
            month = str(row["month"])
            day = str(row["day"])
            new_floder_name = up_id + "-" + down_id + "-" + year + month + day
            new_floder = os.path.join(new_path, new_floder_name)

            old_floder_name = up_id + "-" + down_id + "-" + year + "-" + month + "-" + day + "-流水"

            flag = copy_png_images(os.path.join(d_path, old_floder_name, "png"), new_floder)
            if not flag:
                up_id = str(row["gantry_down"])
                down_id = str(row["gantry_up"])
                old_floder_name = up_id + "-" + down_id + "-" + year + "-" + month + "-" + day + "-流水"
                copy_png_images(os.path.join(d_path, old_floder_name, "png"), new_floder)

            if up_id in event_true_dict.keys():
                event_dict1 = event_true_dict[up_id]
                if down_id == event_dict1["down"]:
                    event_dict_list = event_dict1["list"]
            if event_dict_list:
                for event_dict in event_dict_list:
                    if event_dict["年"] == str(row["year"]) and event_dict["月"] == str(row["month"]) and event_dict[
                        "日"] == str(row["day"]):
                        true_dict = {
                            "eventTime": str(event_dict["年"]) + "-" + str(event_dict["月"]) + "-" + str(
                                event_dict["日"]) + " " + str(event_dict["时"]) + ":" + str(event_dict["分"]),
                            "direction": str(event_dict["方向"]),
                            "pileNumber": str(event_dict["桩号"]),
                            "roadType": str(event_dict["道路类型"]),
                            "eventType": str(event_dict["事故分类"])
                        }
                        true_value_list.append(true_dict)
            json_data = {
                "upGantryId": str(row["gantry_up"]),
                "downGantryId": str(row["gantry_down"]),
                "time": str(row["year"]) + "-" + str(row["month"]) + "-" + str(row["day"]),
                "source": "纳黔高速",
                "trueValueList": true_value_list
            }
            file_path = os.path.join(new_floder, "info.json")
            # 将字典保存为 JSON 文件
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(json_data, f, ensure_ascii=False)
            true_value_list = []


def deal_1():
    n = 0
    reslut_name_list = ["block", "congestion", "deduction"]
    d_path = r"D:\GJ\项目\事故检测\output0319"
    folder_B = r'D:\GJ\项目\事故检测\output0311\output19'
    if not os.path.exists(folder_B):
        os.makedirs(folder_B)
    # 构建 JSON 文件的目标路径
    destination_json_path = os.path.join(folder_B, "truth.json")
    data_list = []
    for dir_path in get_direct_subdirectories(d_path):
        time.sleep(0.1)
        n += 1
        print(n)
        # 定义文件夹 A、B 和 C 的路径
        folder_A = dir_path

        folder_C = os.path.join(folder_B, "algorithm", 'V1.0')

        # 创建文件夹 B 和 C（如果不存在）

        if not os.path.exists(folder_C):
            os.makedirs(folder_C)
        for reslut_name in reslut_name_list:
            new_name = os.path.join(folder_C, reslut_name)
            if not os.path.exists(new_name):
                os.makedirs(new_name)

        # 处理 PNG 图片
        png_folder = os.path.join(folder_A, 'png')
        if os.path.exists(png_folder):
            # 创建文件夹 B 下与 A 同名的文件夹
            folder_B_A = os.path.join(folder_B, "file", os.path.basename(folder_A))
            if not os.path.exists(folder_B_A):
                os.makedirs(folder_B_A)
            for filename in os.listdir(png_folder):
                if filename.endswith('.png'):
                    source_path = os.path.join(png_folder, filename)
                    destination_path = os.path.join(folder_B_A, filename)
                    shutil.copy2(source_path, destination_path)

        # 获取文件夹 A 的名称（不包含路径）
        folder_A_name = os.path.basename(folder_A)
        # 生成对应的 JSON 文件名
        json_filename = f"{folder_A_name}.json"
        # 构建 JSON 文件的源路径
        source_json_path = os.path.join(folder_A, json_filename)
        # # 构建 JSON 文件的目标路径
        # destination_json_path = os.path.join(folder_B, "truth.json")
        # 检查该 JSON 文件是否存在
        if os.path.exists(source_json_path):
            # 复制 JSON 文件
            # shutil.copy2(source_json_path, destination_json_path)
            # 读取原始 JSON 文件内容
            with open(source_json_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
            data["id"] = folder_A_name
            data["truthMark"] = []
            for i in range(len(data["truthValue"])):
                data["truthValue"][i]["eventTime"] = data["truthValue"][i]["eventTime"] + ":00"
                truth_mark = data["truthValue"][i]["eventType"]
                if truth_mark in data["truthMark"]:
                    continue
                else:
                    data["truthMark"].append(truth_mark)
            if len(data["truthMark"]) == 0:
                data["truthMark"].append("未分类")
            data["algorithmMark"] = ["未分类"]

            data_list.append(data)
    # 将更新后的数据写入目标 JSON 文件
    with open(destination_json_path, 'w', encoding='utf-8') as f:
        for data in data_list:
            json.dump(data, f, ensure_ascii=False)
            f.write("\n")


def bbb():
    d_path = r"D:\GJ\项目\事故检测\output0319"
    for dir_path in get_direct_subdirectories(d_path):
        # 定义文件夹 A、B 和 C 的路径
        folder_A = dir_path
        folder_B = r'D:\GJ\项目\事故检测\115'

        # 创建文件夹 B 和 C（如果不存在）
        if not os.path.exists(folder_B):
            os.makedirs(folder_B)

        # 获取文件夹 A 的名称（不包含路径）
        folder_A_name = os.path.basename(folder_A)
        # 生成对应的 JSON 文件名
        json_filename = f"{folder_A_name}.json"
        # 构建 JSON 文件的源路径
        source_json_path = os.path.join(folder_A, json_filename)
        # 检查该 JSON 文件是否存在
        if os.path.exists(source_json_path):
            # 构建 JSON 文件的目标路径
            destination_json_path = os.path.join(folder_B, json_filename)
            # 复制 JSON 文件
            shutil.copy2(source_json_path, destination_json_path)


def csv_to_list(path):
    # 示例数据
    df = pd.read_csv(path)
    df_data = df.to_dict(orient='records')
    # 创建一个空列表用于保存所有记录
    all_records = []
    # 定义门架ID
    gantry_a_id = os.path.basename(path).split('.')[0].split('-')[1]
    gantry_b_id = os.path.basename(path).split('.')[0].split('-')[2]

    # gantry_a_id = os.path.basename(path).split('.')[0][4:].split(',')[0]
    # gantry_b_id = os.path.basename(path).split('.')[0][4:].split(',')[1].split('-')[0]

    # 遍历每一行数据
    for row in df_data:
        vlp = row['vlp']
        feevehicletype = row['feevehicletype']
        # 如果有经过门架A的时间，则添加一条记录
        if pd.notna(row['transtime_up']):
            transtime = pd.to_datetime(row['transtime_up'], format='%Y/%m/%d %H:%M:%S')
            record = {'gantry_id': gantry_a_id, 'vlp': vlp, 'feevehicletype': feevehicletype, 'transtime': transtime}
            all_records.append(record)

        # 如果有经过门架B的时间，则添加一条记录
        if pd.notna(row['transtime_down']):
            transtime = pd.to_datetime(row['transtime_down'], format='%Y/%m/%d %H:%M:%S')
            record = {'gantry_id': gantry_b_id, 'vlp': vlp, 'feevehicletype': feevehicletype, 'transtime': transtime}
            all_records.append(record)

    # 按照过车时间对记录进行排序
    all_records_sorted = sorted(all_records, key=lambda x: x['transtime'])
    return all_records_sorted


def get_files_containing_substring(directory, substring):
    file_name = None
    # 遍历指定目录下的所有文件
    for filename in os.listdir(directory):
        # 构建完整的文件路径
        full_path = os.path.join(directory, filename)
        # 检查是否为文件
        if os.path.isfile(full_path):
            # 检查文件名是否包含指定的子字符串
            if substring in filename:
                file_name = full_path
    return file_name


def save_json_for_csv(path):
    json_path = r"D:\GJ\项目\事故检测\json_chuangao"
    if not os.path.exists(json_path):
        os.makedirs(json_path)
    csv_path = get_files_containing_substring(path, 'all_')
    all_records_sorted = csv_to_list(csv_path)
    old_name = os.path.basename(csv_path).split('.')[0]
    # new_file = "all_" + old_name.split('-')[1] + "-" + old_name.split('-')[0][4:].split(',')[0] + '-' + old_name.split('-')[0][4:].split(',')[1]
    new_path = os.path.join(json_path, old_name + '.json')
    with open(new_path, 'w', encoding='utf-8') as f:
        for row in all_records_sorted:
            row['transtime'] = row['transtime'].strftime('%Y-%m-%d %H:%M:%S')
            json.dump(row, f, ensure_ascii=False)
            f.write('\n')


def write_json_1():
    folder_path = 'D:\GJ\项目\事故检测\json_chuangao'
    result = {}
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if int(str(file)[4:12]) >= 20230101:
                file_path = os.path.join(root, file)  # 获取完整文件路径
                print("2025:", file)
                with open(file_path, 'r', encoding='utf-8') as f:
                    index = 0
                    for line in f:
                        index += 1
                        data_json = json.loads(line.strip())
                        data_json['gantry_id'] = data_json['gantry_id'] + "_" + str(file).split('.')[0]
                        if index not in result.keys():
                            result[index] = [data_json]
                        else:
                            result[index].append(data_json)
            else:
                file_path = os.path.join(root, file)  # 获取完整文件路径
                print("2024:", file)
                with open(file_path, 'r', encoding='utf-8') as ff:
                    data = ff.read()
                    data_json = json.loads(data)
                    for index, data_one in enumerate(data_json):
                        if index not in result.keys():
                            data_one['gantry_id'] = data_one['gantry_id'] + "_" + str(file).split('.')[0]
                            result[index] = [data_one]
                        else:
                            data_one['gantry_id'] = data_one['gantry_id'] + "_" + str(file).split('.')[0]
                            result[index].append(data_one)
    with open(r'D:\GJ\项目\事故检测\result_20250319.json', 'a', encoding='utf-8') as file_w:
        for k, v in result.items():
            file_w.write(str(v).replace("'", '"') + "\n")

def write_json():
    folder_path = r'D:\GJ\项目\事故检测\all_json'
    result = {}
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if 20250127 <= int(str(file)[4:12]) <= 20250226:
                file_path = os.path.join(root, file)  # 获取完整文件路径
                print("2025:", file)
                with open(file_path, 'r', encoding='utf-8') as f:
                    index = 0
                    for line in f:
                        index += 1
                        data_json = json.loads(line.strip())
                        data_json['gantry_id'] = data_json['gantry_id'] + "_" + str(file).split('.')[0]
                        if index not in result.keys():
                            result[index] = [data_json]
                        else:
                            result[index].append(data_json)
            # elif 20240701 <= int(str(file)[4:12]) < 20250101:
            #     file_path = os.path.join(root, file)  # 获取完整文件路径
            #     print("2024:", file)
            #     with open(file_path, 'r', encoding='utf-8') as ff:
            #         data = ff.read()
            #         data_json = json.loads(data)
            #         for index, data_one in enumerate(data_json):
            #             if index not in result.keys():
            #                 data_one['gantry_id'] = data_one['gantry_id'] + "_" + str(file).split('.')[0]
            #                 result[index] = [data_one]
            #             else:
            #                 data_one['gantry_id'] = data_one['gantry_id'] + "_" + str(file).split('.')[0]
            #                 result[index].append(data_one)
    with open(r'D:\GJ\项目\事故检测\result_20250127.json', 'w', encoding='utf-8') as file_w:
        for k, v in result.items():
            file_w.write(str(v).replace("'", '"') + "\n")


def get_hou_json():
    folder_path = r"D:\GJ\项目\事故检测\ceshi0319"
    old_path = r"D:\GJ\项目\事故检测\111_all"
    folder_B = r"D:\GJ\项目\事故检测\115"
    if not os.path.exists(folder_B):
        os.makedirs(folder_B)
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            name = file[4:]
            source_json_path = os.path.join(old_path, name)
            # 检查该 JSON 文件是否存在
            if os.path.exists(source_json_path):
                # 构建 JSON 文件的目标路径
                destination_json_path = os.path.join(folder_B, name)
                # 复制 JSON 文件
                shutil.copy2(source_json_path, destination_json_path)
            else:
                print(f"JSON 文件 {source_json_path} 不存在")


def move_real():
    folder_a = r"D:\GJ\项目\事故检测\output0305_3\file"
    folder_b = r'D:\GJ\项目\铜锣山\0306_1\save_png\save_png'

    for root, dirs, files in os.walk(folder_a):
        for dir_name in dirs:
            b_dir_path = os.path.join(folder_b, dir_name)
            if os.path.isdir(b_dir_path):
                for sub_root, sub_dirs, sub_files in os.walk(b_dir_path):
                    for file in sub_files:
                        if file.endswith('.png'):
                            source_file_path = os.path.join(sub_root, file)
                            target_dir_path = os.path.join(root, dir_name)
                            if not os.path.exists(target_dir_path):
                                print(f"目标文件夹 {target_dir_path} 不存在，跳过复制操作")
                                continue
                            shutil.copy2(source_file_path, target_dir_path)


if __name__ == '__main__':
    # lindian()
    # mianguang()
    # naqian()
    # 修改json文件，添加空字段
    # deal_1()

    # move_real()

    for dir_path in get_direct_subdirectories(r'D:\GJ\项目\事故检测\output0319'):
        if os.path.exists(os.path.join(dir_path, 'png')):
            save_json_for_csv(dir_path)
    # 直接复制json
    # bbb()

    # write_json()
    # write_json_1()

    # get_hou_json()

    print("1")








    # # 获取非递归文件夹示例--get_direct_subdirectories()
    # d_path = r'D:\GJ\项目\铜锣山\data\data_output'
    # new_path = r'D:\GJ\项目\铜锣山\data\bbb'
    # for dir_path in get_direct_subdirectories(d_path):
    #     print(dir_path)

    # 图片拼接示例--calculate_crop_box_by_ratio()、crop_and_concat_images()
    # ratios = [(0.9, 0.78), (0.9, 0.78), (0.9, 0.78)]  # 示例比例
    # d_path = r'D:\GJ\项目\铜锣山\data\data_output'
    # for dir_path in get_direct_subdirectories(d_path):
    #     print(dir_path)
    #     png_path = os.path.join(dir_path, "png")
    #     filename1 = os.path.join(png_path, "mate_flow_data.png")
    #     filename3 = os.path.join(png_path, "car_time_data.png")
    #     filename2 = os.path.join(png_path, "time_duration_data_car.png")
    #     outname = os.path.join(png_path, "combined.png")
    #     img_paths = [filename1, filename2, filename3]
    #     images = [Image.open(path) for path in img_paths]
    #     crop_boxes = [calculate_crop_box_by_ratio(img, ratio) for img, ratio in zip(images, ratios)]
    #     crop_and_concat_images(img_paths, outname, crop_boxes)

